package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;


public class FragmentFabric extends Fragment implements View.OnClickListener {
    public static String TAG=FragmentA.class.getName();
    public static final int MSG_FocusBarcode = 1001;
    public static final int MSG_SCANBARCODE = 1002;
    public static final int MSG_QuestionOver = 1003;
    public static final int MSG_SUBMIT = 1004;
    public static final int MSG_WEIGHT = 1005;
    public static final int MSG_LENGTH = 1006;
    public static final int MSG_ERRMSG =1007;
    public static final int MSG_Purchase =1008;
    public static final int MSG_SAVE =1009;
    public static final int MSG_ShowPurchase=1010;


    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    ImageButton btn_editBarcode;
    int curMeasurePostion = -1,curProcPosition = -1;
    String curLoginUserNo,curLoginUser,curDepartNo,curDepart,curServiceDir = "",curServiceUrl = "",CPUID="";
    String WeightStr = "",PrBarcode="",LengthStr = "",FabricDeID = "";
    Toast curToast;
    EditText edt_CurLenValue,edt_CurSelect,edt_PieceLength,edt_RealWeight,edt_PieceNo, edit_RealFabricWidth,edt_PieceWeight,edt_VatNo,edt_barcode,edit_findOrderNo,edt_BadWeight,edt_RectNo;
    JSONArray badJSON,fabricJSON,questionJson,resultJSON;
    TextView txt_BaleName,txt_Color, txt_StyleNo,txt_FabricWidth,txt_GramWeight,txt_HintInfo,txt_OrderNo,txt_Question,txt_TotalLen,txt_TotalPiece,txt_TotalWeight,txt_NeedWeight,txt_ReadyWeight;
    TextView txt_PackEmpName,txt_CheckEmpName;
    SQLiteDatabase tmpdb;
    GridView gv_Question;
    ListView lv_BadList,purchaseListGrid;
    BadListAdapter badListAdapter;
    String selBaleCode="",selBaleName = "",selColor = "",selFabricCode = "",selFabricElement = "", selFabricQuestion = "",selFabricWidth = "",
            selGramWeight = "",selKeyID = "",selOrderNo = "",selNeedWeight="",selReadyWeight="",selStyleNo="",selVatNo="",selKeyFormNo="",selOwenNum="";
    Button btn_One,btn_Two,btn_Three,btn_Four,btn_UpdateQuestion,btn_clearCheck,btn_submitCheck,btn_find,
            btn_Query,btn_QuestionAdd,btn_QuestionClear,btn_ManuQuestion;
    Button view_oneBtn,view_twoBtn,view_threeBtn,view_fourBtn,view_fiveBtn,view_sixBtn,view_sevenBtn,view_eightBtn,view_nineBtn,
            view_zeroBtn,view_pointBtn,view_nextBtn,view_delBtn,view_clearBtn,view_affirmBtn,view_saveWeight;
    JSONArray PurchaseJSONArray,employeeJson;
    CheckBox chk_isYT,chk_isCJ;
    String PrFabricMaID="";
    JSONArray headJSON,detailJSON;
    LinearLayout templetlisthead;
    ListView selectTempletList;
    String selPackEmpNo="",selPackEmpName="",selRectNo="",selBadWeight="";
    private ProgressDialog waitDialog = null;
    private FragmentFabricCallBack mFragmentFabricCallBack;
    public interface FragmentFabricCallBack {
        // 里面传个值@param Map<String,Object>适应多种类型;
        void FragmentFabricWorkAndTransParams(Map<String, Object> Params);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (!(activity instanceof FragmentFabricCallBack)) {
            throw new IllegalStateException("MainActivity必须实现FragmentCCallBack接口");
        }
        mFragmentFabricCallBack=(FragmentFabricCallBack) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mFragmentFabricCallBack=null;
    }

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public FragmentFabric() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerFabric(new MainActivity.OnTransParamsListenerFabric() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        System.out.println(mParams);
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(getClass().getName(),"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            System.out.println("1");
                            curLoginUser=mParams.get("LoginUser").toString();
                            System.out.println("2");
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            System.out.println("3");
                            curServiceDir=mParams.get("ServiceDir").toString();
                            System.out.println("4");
                            curDepartNo=mParams.get("DepartNo").toString();
                            System.out.println("5");
                            curDepart=mParams.get("Depart").toString();
                            System.out.println("6");
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(getClass().getName(),"LoginParam------------------>2");
                            getEmployee();
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = MSG_FocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (paramComm == "Weight") {
                            WeightStr = mParams.get("Weight").toString();
                            System.out.println("FragmentA接收到重量:"+WeightStr);
                            if (isNumeric(WeightStr) == true) {
                                Message message = new Message();
                                Bundle bundle = new Bundle();
                                bundle.putString("Weight", WeightStr);
                                message.setData(bundle);
                                message.what = MSG_WEIGHT;
                                fragmentHandler.removeMessages(message.what);
                                fragmentHandler.sendMessage(message);
                            }
                        }
                        if (paramComm == "Length") {
                            LengthStr = mParams.get("Length").toString();
                            if (isNumeric(LengthStr) == true) {
                                Message message = new Message();
                                Bundle bundle = new Bundle();
                                bundle.putString("Length", LengthStr);
                                message.setData(bundle);
                                message.what = MSG_LENGTH;
                                fragmentHandler.removeMessages(message.what);
                                fragmentHandler.sendMessage(message);
                                return;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void getEmployee(){
        String SqlComm = "Exec KeyPoint_PBFabricGetEmployee @OperType='GetEmployee',@DepartNo='"+curDepartNo+"',@LoginUserNo='"+curLoginUserNo+"',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }
    //显示工序选择
    private void showSelectEmployee(final TextView textView){
        if (employeeJson==null) {
            getEmployee();
            return;
        }
        try {
            headJSON=new JSONArray("[{\"TitleName\":\"DepartmentNo\",\"TitleText\":\"组别编号\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"Department\",\"TitleText\":\"组别名称\",\"TxtSize\":18,\"TxtWidth\":120,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"EmployeeNo\",\"TitleText\":\"员工编号\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"Employee\",\"TitleText\":\"员工姓名\",\"TxtSize\":18,\"TxtWidth\":120,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");


        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="组别选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        detailJSON=employeeJson;
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    if (view.isActivated()) detailJSON.optJSONObject(position).put("SelSign",1);
                    else detailJSON.optJSONObject(position).put("SelSign",0);
                    if (detailJSON.optJSONObject(position).has("EmployeeNo")==true)
                        selPackEmpNo=detailJSON.optJSONObject(position).getString("EmployeeNo");
                    if (detailJSON.optJSONObject(position).has("Employee")==true)
                        selPackEmpName=detailJSON.optJSONObject(position).getString("Employee");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //显示表明细
        SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(getContext());
        selectTempletList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
        selectTempletList.setAdapter(selectTempletListAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        String tmpEmployee="";
                        for (int i=0;i<detailJSON.length();i++){
                            if (detailJSON.optJSONObject(i).has("SelSign")){
                                try {
                                    if (detailJSON.optJSONObject(i).getInt("SelSign")==1) {
                                        detailJSON.optJSONObject(i).put("SelSign",0);
                                        if (tmpEmployee.length() > 0) {
                                            tmpEmployee = tmpEmployee + ";" + detailJSON.optJSONObject(i).getString("Employee");
                                        } else
                                            tmpEmployee = detailJSON.optJSONObject(i).getString("Employee");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        if (tmpEmployee.length()>0) selPackEmpName=tmpEmployee;
                        if (selPackEmpName.length() == 0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请点击要选择的内容！");
                            curToast.show();
                        } else{
                            textView.setText(selPackEmpName);
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    for (int i=0;i<detailJSON.length();i++){
                        if (detailJSON.optJSONObject(i).has("SelSign")){
                            try {
                                if (detailJSON.optJSONObject(i).getInt("SelSign")==1) {
                                    detailJSON.optJSONObject(i).put("SelSign",0);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    textView.setText("");
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 600;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);
    }



    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return detailJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<detailJSON.length())
                    return detailJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,60));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<detailJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (detailJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = detailJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (detailJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= detailJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }


    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }



    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_fabric, container, false);
        InitView(root);
        badListAdapter = new BadListAdapter(getContext());
        GetFabricCode();
        FabricDeID = UUID.randomUUID().toString();
        ClearAllData();
        System.out.println(getClass().getName()+"_onCreateView");
        return root;
    }

    private void nextEdit() {
        /*
        if (edt_CurSelect.getId() == R.id.edt_VatNo) {
            setActiveEdt(edt_PieceNo);
            return;
        }
        if (edt_CurSelect.getId() == R.id.edt_PieceNo) {
            setActiveEdt(edt_PieceStart);
            return;
        }
         */
        if (edt_CurSelect.getId() == R.id.edit_RealFabricWidth) {
            setActiveEdt(edt_PieceLength);
            return;
        }
        if (edt_CurSelect.getId() == R.id.edt_PieceLength) {
            setActiveEdt(edt_RealWeight);
            return;
        }
        if (edt_CurSelect.getId() ==  R.id.edt_RealWeight) {
            setActiveEdt(edt_PieceWeight);
            return;
        }
    }

    private void totalPiece() {
        float TotalLen = 0.0F;
        float TotalPiece=0.0F;
        float TotalWeight = 0.0F;
        if (fabricJSON != null) {
            for (int i=0;i < fabricJSON.length();i++) {
                try {
                    TotalLen += Float.parseFloat(fabricJSON.optJSONObject(i).getString("PieceLength"));
                    TotalWeight += Float.parseFloat(fabricJSON.optJSONObject(i).getString("PieceWeight"));
                    TotalPiece += 1;
                } catch (JSONException jSONException) {
                    jSONException.printStackTrace();

                }
            }
        }
        txt_TotalLen.setText(String.valueOf(TotalLen));
        txt_TotalPiece.setText(String.valueOf(TotalPiece));
        txt_TotalWeight.setText(String.valueOf(TotalWeight));
    }

    //显示可以复制的订单列表;
    private void showPurchaseList() {
        //显示到工序中;
        final PurchaseListAdapter purchaseListAdapter=new PurchaseListAdapter(getContext());
        purchaseListGrid.setAdapter(purchaseListAdapter);
    }
    //工序表格适配器;
    public final class PurchaseListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public PurchaseListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return PurchaseJSONArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return PurchaseJSONArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_fabric_finditem, null, false);
            convertView.setBackground(getResources().getDrawable(R.drawable.orderlist_selector));
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            int textColor=getResources().getColor(R.color.text_black);
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.item_OrderNo);// 显示文字
                if (PurchaseJSONArray.optJSONObject(position).has("OrderNo")) {
                    tv.setText(PurchaseJSONArray.optJSONObject(position).get("OrderNo").toString());
                    tv.setTextColor(textColor);
                }
                tv = (TextView) convertView.findViewById(R.id.item_StyleNo);// 显示文字
                if (PurchaseJSONArray.optJSONObject(position).has("StyleNo")) {
                    tv.setText(PurchaseJSONArray.optJSONObject(position).get("StyleNo").toString());
                    tv.setTextColor(textColor);
                }
                if (PurchaseJSONArray.optJSONObject(position).has("BaleName")) {
                    tv = (TextView) convertView.findViewById(R.id.item_BaleName);// 显示文字
                    tv.setText(PurchaseJSONArray.optJSONObject(position).get("BaleName").toString());
                    tv.setTextColor(textColor);
                }
                if (PurchaseJSONArray.optJSONObject(position).has("Color")) {
                    tv = (TextView) convertView.findViewById(R.id.item_Color);// 显示文字
                    tv.setText(PurchaseJSONArray.optJSONObject(position).get("Color").toString());
                    tv.setTextColor(textColor);
                }
                if (PurchaseJSONArray.optJSONObject(position).has("VatNo")) {
                    tv = (TextView) convertView.findViewById(R.id.item_VatNo);// 显示文字
                    tv.setText(PurchaseJSONArray.optJSONObject(position).get("VatNo").toString());
                    tv.setTextColor(textColor);
                }
                if (PurchaseJSONArray.optJSONObject(position).has("FabricWidth")) {
                    tv = (TextView) convertView.findViewById(R.id.item_FabricWidth);// 显示文字
                    tv.setText(PurchaseJSONArray.optJSONObject(position).get("FabricWidth").toString());
                    tv.setTextColor(textColor);
                }
                if (PurchaseJSONArray.optJSONObject(position).has("GramWeight")) {
                    tv = (TextView) convertView.findViewById(R.id.item_GramWeight);// 显示文字
                    tv.setText(PurchaseJSONArray.optJSONObject(position).get("GramWeight").toString());
                    tv.setTextColor(textColor);
                }
                if (PurchaseJSONArray.optJSONObject(position).has("NeedWeight")) {
                    tv = (TextView) convertView.findViewById(R.id.item_NeedWeight);// 显示文字
                    tv.setText(PurchaseJSONArray.optJSONObject(position).get("NeedWeight").toString());
                    tv.setTextColor(textColor);
                }
                if (PurchaseJSONArray.optJSONObject(position).has("ReadyWeight")) {
                    tv = (TextView) convertView.findViewById(R.id.item_ReadyWeight);// 显示文字
                    tv.setText(PurchaseJSONArray.optJSONObject(position).get("ReadyWeight").toString());
                    tv.setTextColor(textColor);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","PurchaseListAdapter_position:"+position);
            return convertView;
        }
    }

    public void OpenCreateDB() {
        if (tmpdb == null)
            tmpdb = ((MainActivity)getActivity()).mainDB;
    }

    private void checkSaveFabric(final String paramOrderNo,final String paramBaleCode, final String paramBaleName,final String paramColor,final String paramVatNo,final String paramPieceNo,final String paramOwen) {
        //线程直接保存不经过WebService;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                //将数据读到JSONArray;
                String FabricMaID = UUID.randomUUID().toString();
                PrFabricMaID=FabricMaID;
                try {
                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement("Exec KeyPointPBFabricDe_CheckRepeat @Barcode=?,@OrderNo=?,@BaleCode=?,@BaleName=?,@Color=?,@VatNo=?,@PieceNo=?,@OwenNum=?");
                    pstmt.setString(1, PrBarcode);
                    pstmt.setString(2, paramOrderNo);
                    pstmt.setString(3, paramBaleCode);
                    pstmt.setString(4, paramBaleName);
                    pstmt.setString(5, paramColor);
                    pstmt.setString(6, paramVatNo);
                    pstmt.setString(7, paramPieceNo );
                    pstmt.setString(8, paramOwen );
                    ResultSet resultSet=pstmt.executeQuery();
                    System.out.println("checkSaveFabric--A"+resultSet.getRow());
                    if (resultSet.next()){
                        System.out.println("checkSaveFabric--B");
                        if (isExistColumn(resultSet,"Result")){
                            if (resultSet.getString(resultSet.findColumn("Result")).equals("Y")) {
                                System.out.println("checkSaveFabric--C");
                                //关闭ProgressDialog
                                Message msg = new Message();
                                msg.what = MSG_SAVE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                        }
                        if (isExistColumn(resultSet,"ErrInfo")){
                            System.out.println("checkSaveFabric--D");
                            Message msg=new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("Hint",resultSet.getString(resultSet.findColumn("ErrInfo")));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    }
                    return;
                }
                catch (SQLException  ex) {
                    ex.printStackTrace();

                }
            }
        };
        new Thread(run).start();

    }

    /**
     * 判断查询结果集中是否存在某列
     * @param rs 查询结果集
     * @param columnName 列名
     * @return true 存在; false 不存咋
     */
    public boolean isExistColumn(ResultSet rs, String columnName) {
        try {
            if (rs.findColumn(columnName) > 0 ) {
                return true;
            }
        }
        catch (SQLException e) {
            return false;
        }

        return false;
    }



    private void putFabricList(final String paramOrderNo, final String paramBaleCode, final String paramBaleName, final String paramColor,
                               final String paramFabricElement,final String paramFabricWidth,final String paramGramWeight,final String paramNeedWeight,
                               final String paramRectNo, final String paramBadWeight) {
        JSONArray jsonArray = fabricJSON;
        if (jsonArray != null) {
            if (jsonArray.length() == 0)
                return;
            System.out.println("curLoginUserNo:"+curLoginUserNo+" curLoginUser:"+curLoginUser);
            //线程直接保存不经过WebService;
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    //将数据读到JSONArray;
                    String FabricMaID = UUID.randomUUID().toString();
                    PrFabricMaID=FabricMaID;
                    try {
                        System.out.println("A");
                        PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement("Insert into KeyPointPBFabricBad(FabricBadID,FabricMaID,FabricDeID,FabricCode,FabricQuestion,Place,Deduct) values(newid(),?,?,?,?,?,?)");
                        Cursor cursor = tmpdb.rawQuery("Select FabricDeID,FabricCode,FabricQuestion,Place,Deduct from  FabricBad  Order by ID", null);
                        while (cursor.moveToNext()) {
                            pstmt.setString(1, FabricMaID);
                            pstmt.setString(2, cursor.getString(cursor.getColumnIndex("FabricDeID")));
                            pstmt.setString(3, cursor.getString(cursor.getColumnIndex("FabricCode")));
                            pstmt.setString(4, cursor.getString(cursor.getColumnIndex("FabricQuestion")));
                            pstmt.setString(5, cursor.getString(cursor.getColumnIndex("Place")));
                            pstmt.setString(6, cursor.getString(cursor.getColumnIndex("Deduct")));
                            System.out.println("KeyPointFabricBad-->Place"+cursor.getString(cursor.getColumnIndex("FabricCode")));
                            System.out.println("KeyPointFabricBad-->Place"+cursor.getString(cursor.getColumnIndex("FabricQuestion")));
                            System.out.println("KeyPointFabricBad-->Place"+cursor.getString(cursor.getColumnIndex("Place")));
                            System.out.println("KeyPointFabricBad-->Deduct"+cursor.getString(cursor.getColumnIndex("Deduct")));
                            pstmt.executeUpdate();
                        }
                        System.out.println("B");
                        System.out.println(fabricJSON);
                        pstmt.close();
                        pstmt = DBUtil.getSQLConnection().prepareStatement("Insert into KeyPointPBFabricDe(FabricDeID,FabricMaID,KeyID,VatNo,PieceNo,PieceStart,PieceMiddle,PieceEnd,PieceLength,PieceWeight,RealWeight,RealFabricWidth) values(?,?,?,?,?,?,?,?,?,?,?,?)");
                        for (int i = 0; i < fabricJSON.length(); i++) {
                            pstmt.setString(1, fabricJSON.getJSONObject(i).getString("FabricDeID"));
                            pstmt.setString(2, FabricMaID);
                            pstmt.setString(3, fabricJSON.getJSONObject(i).getString("KeyID"));
                            pstmt.setString(4, fabricJSON.getJSONObject(i).getString("VatNo"));
                            pstmt.setString(5, fabricJSON.getJSONObject(i).getString("PieceNo"));
                            pstmt.setString(6, fabricJSON.getJSONObject(i).getString("PieceStart"));
                            pstmt.setString(7, fabricJSON.getJSONObject(i).getString("PieceMiddle"));
                            pstmt.setString(8, fabricJSON.getJSONObject(i).getString("PieceEnd"));
                            pstmt.setString(9, fabricJSON.getJSONObject(i).getString("PieceLength"));
                            pstmt.setString(10, fabricJSON.getJSONObject(i).getString("PieceWeight"));
                            pstmt.setString(11, fabricJSON.getJSONObject(i).getString("RealWeight"));
                            pstmt.setString(12, fabricJSON.getJSONObject(i).getString("RealFabricWidth"));
                            System.out.println("KeyPointFabricDe-"+i+"->PieceNo"+fabricJSON.getJSONObject(i).getString("PieceNo"));
                            System.out.println("KeyPointFabricDe-"+i+"->PieceStart"+fabricJSON.getJSONObject(i).getString("PieceStart"));
                            System.out.println("KeyPointFabricDe-\"+i+\"->PieceMiddle"+fabricJSON.getJSONObject(i).getString("PieceMiddle"));
                            System.out.println("KeyPointFabricDe-\"+i+\"->PieceEnd"+fabricJSON.getJSONObject(i).getString("PieceEnd"));
                            System.out.println("KeyPointFabricDe-\"+i+\"->PieceLength"+fabricJSON.getJSONObject(i).getString("PieceLength"));
                            System.out.println("KeyPointFabricDe-\"+i+\"->PieceWeight"+fabricJSON.getJSONObject(i).getString("PieceWeight"));
                            System.out.println("KeyPointFabricDe-\"+i+\"->RealWeight"+fabricJSON.getJSONObject(i).getString("RealWeight"));
                            System.out.println("KeyPointFabricDe-\"+i+\"->RealFabricWidth"+fabricJSON.getJSONObject(i).getString("RealFabricWidth"));
                            pstmt.executeUpdate();
                        }
                        System.out.println("C");
                        pstmt.close();
                        pstmt = DBUtil.getSQLConnection().prepareStatement("Insert into KeyPointPBFabricMa(FabricMaID,Barcode,OrderNo,BaleCode,BaleName,Color,FabricElement,FabricWidth,GramWeight,NeedWeight," +
                                "OperatorNo,Operator,SaveTime,StyleNo,KeyFormNo,isYT,isCJ,PackEmpName,CheckEmpName,RectNo,BadWeight) values(?,?,?,?,?,?,?,?,?,?,?,?,getdate(),?,?,?,?,?,?,?,?)");
                        pstmt.setString(1, FabricMaID);
                        pstmt.setString(2, PrBarcode);
                        pstmt.setString(3, paramOrderNo);
                        pstmt.setString(4, paramBaleCode);
                        pstmt.setString(5, paramBaleName);
                        pstmt.setString(6, paramColor);
                        pstmt.setString(7, paramFabricElement);
                        pstmt.setString(8, paramFabricWidth.length()>0?paramFabricWidth:"0");
                        pstmt.setString(9, paramGramWeight.length()>0?paramGramWeight:"0");
                        pstmt.setString(10, paramNeedWeight.length()>0?paramNeedWeight:"0");
                        pstmt.setString(11, curLoginUserNo);
                        pstmt.setString(12, curLoginUser);
                        pstmt.setString(13, selStyleNo);
                        pstmt.setString(14, selKeyFormNo);
                        if (chk_isYT.isChecked())  pstmt.setString(15, "Y");
                        else  pstmt.setString(15, "N");
                        if (chk_isCJ.isChecked())  pstmt.setString(16, "Y");
                        else  pstmt.setString(16, "N");
                        pstmt.setString(17,txt_PackEmpName.getText().toString());
                        pstmt.setString(18, txt_CheckEmpName.getText().toString());
                        pstmt.setString(19, paramRectNo.length()>0?paramRectNo:"0");
                        pstmt.setString(20, paramBadWeight.length()>0?paramBadWeight:"0" );
                        System.out.println("KeyPointFabricMa-->paramFabricWidth"+paramFabricWidth);
                        System.out.println("KeyPointFabricMa-->paramGramWeight"+paramGramWeight);

                        pstmt.executeUpdate();
                        pstmt.close();
                        String SqlComm = "Exec KeyPoint_FabricPBSaveTrans @OperType='SaveTrans',@FabricMaID='" + FabricMaID + "',@Barcode='"+PrBarcode+"',@UserNo='"+curLoginUserNo+"',@UserName='"+curLoginUser+"'";
                        ReadSQLData(SqlComm);
                        return;
                    }
                    catch (SQLException | JSONException ex) {
                        ex.printStackTrace();
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("Hint","保存数据出错!"+ex.getMessage());
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                }
            };
            new Thread(run).start();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("requestCode:"+requestCode+" resultCode:"+resultCode);
        if (requestCode == 1000 && resultCode == 1001) {
            Bundle bundle = data.getExtras();
            selOrderNo = bundle.getString("selOrderNo");
            selBaleCode = bundle.getString("selBaleCode");
            selBaleName = bundle.getString("selBaleName");
            selColor = bundle.getString("selColor");
            selFabricElement = bundle.getString("selFabricElement");
            selFabricWidth = bundle.getString("selFabricWidth");
            selGramWeight = bundle.getString("selGramWeight");
            txt_OrderNo.setText(selOrderNo);
            txt_BaleName.setText(selBaleName);
            txt_Color.setText(selColor);
            txt_StyleNo.setText(selStyleNo);
            txt_FabricWidth.setText(selFabricWidth);
            txt_GramWeight.setText(selGramWeight);
            edt_VatNo.setText("");
            edt_PieceNo.setText("");
            edit_RealFabricWidth.setText("");
            edt_PieceLength.setText("");
            edt_PieceWeight.setText("");
        }
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                String resultMsg="";
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_ERRMSG:
                        //提示提交完成，需确认;
                        Bundle bundle1=msg.getData();
                        resultMsg=bundle1.getString("Hint");
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                                .setTitle("系统提示").setMessage(resultMsg)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        break;
                    case MSG_FocusBarcode:
                        //任意消息来均置焦点
                        if (edt_barcode.isFocused()==false) setEditBarcodeFocus();
                        else edt_barcode.selectAll();
                        break;
                    case MSG_SCANBARCODE:
                        fillScreen();
                        setEditBarcodeFocus();
                        break;
                    case MSG_QuestionOver:
                        GetFabricCode();
                        break;
                    case MSG_SUBMIT:
                        //发送米数清零;
                        fragmentParams.clear();
                        fragmentParams.put("ParamComm","LengthReset");//命令;
                        fragmentParams.put("Text","C");//命令;
                        mFragmentFabricCallBack.FragmentFabricWorkAndTransParams(fragmentParams);
                        fillScreen();
                        break;
                    case MSG_SAVE:
                        affirmFabric();
                        break;
                    case MSG_WEIGHT:
                        if (isNumeric(WeightStr)==true) {
                            float weight=Float.parseFloat(WeightStr);
                            edt_PieceWeight.setText(String.valueOf(weight/1000));
                            CalcLength(edt_PieceWeight.getText().toString());
                        }
                        break;
                    case MSG_LENGTH:
                        edt_CurLenValue.setText(LengthStr);
                        edt_PieceLength.setText(LengthStr);
                        break;
                    case MSG_ShowPurchase:
                        showSelPurchase();
                    case MSG_Purchase:
                        showPurchaseList();
                        break;
                    default:
                        break;
                }
            }
        }
    };

    private void CalcLength(String weightStr) {
        //根据门幅加克重计算理论长度;
        if (weightStr.length()==0) return;
        if (isNumeric(weightStr)){
            String RealFabricWidth=edit_RealFabricWidth.getText().toString();
            String RealWeight=edt_RealWeight.getText().toString();
            if (RealFabricWidth.length()>0 && RealWeight.length()>0){
                try {
                    if (Float.parseFloat(RealFabricWidth)>0 && Float.parseFloat(RealWeight)>0) {
                        double len = Float.parseFloat(weightStr) * 1000*100 / (Float.parseFloat(RealFabricWidth) * Float.parseFloat(RealWeight));
                        edt_PieceLength.setText(String.valueOf(BigDecimal.valueOf(((float) len)).setScale(2, BigDecimal.ROUND_CEILING)));
                    } else {
                        Log.d(TAG, "CalcLength: 数据异常");
                    }
                }catch (Exception e)
                {
                    curToast.setText(e.getMessage());
                    curToast.show();
                }
            }


        }
    }

    private void scanBarcodeData(String paramBarcode) {
        playRingtone();
        PrBarcode = paramBarcode;
        try {
            resultJSON = new JSONArray("[]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        String SqlComm="Exec KeyPoint_PBFarbicScan @Barcode='"+paramBarcode+"',@OPERTYPE='SCANBARCODE',@OrderNo='"+txt_OrderNo.getText().toString()
                +"',@UserNo='"+curLoginUserNo+"',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }

    private void ClearAllData() {
        try {
            fabricJSON = new JSONArray("[]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        if (tmpdb == null) OpenCreateDB();
        tmpdb.execSQL("Delete from FabricBad");
        ClearScreen();
        ClearBadData();
    }

    private void ClearBadData() {
        try {
            badJSON = new JSONArray("[]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        lv_BadList.setAdapter((ListAdapter)badListAdapter);
    }

    private void ClearScreen() {
        txt_Question.setText("");
        edt_PieceNo.setText("");
        //edit_RealFabricWidth.setText("");
        edt_PieceLength.setText("");
        edt_PieceWeight.setText("");
        //edt_RealWeight.setText("");
        edt_BadWeight.setText("");
        setActiveEdt(edit_RealFabricWidth);
        try {
            badJSON = new JSONArray("[]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        lv_BadList.setAdapter((ListAdapter)badListAdapter);
    }

    private void GetFabricCode() {
        System.out.println("GetFabricCode()");
        if (tmpdb == null)
            OpenCreateDB();
        try {
            questionJson = new JSONArray("[]");
            Cursor cursor = tmpdb.rawQuery("Select FabricCode,FabricQuestion from  FabricCode  Order by ID", null);
            while (cursor.moveToNext()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("FabricCode", cursor.getString(cursor.getColumnIndex("FabricCode")));
                jsonObject.put("FabricQuestion", cursor.getString(cursor.getColumnIndex("FabricQuestion")));
                questionJson.put(jsonObject);
            }
            QuestionGridAdapter questionGridAdapter = new QuestionGridAdapter(getContext());
            gv_Question.setAdapter((ListAdapter)questionGridAdapter);
            return;
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
            return;
        }
    }

    private void setActiveEdt(EditText paramEditText) {
        EditText editText = edt_CurSelect;
//        if (edt_CurSelect!=null) {
//            if (editText.getId() == R.id.edt_VatNo) view_pointBtn.setText("-");
//            else view_pointBtn.setText(".");
//        }
        if (editText != null)
            editText.setBackground(null);
        edt_CurSelect = paramEditText;
        edt_CurSelect.setBackgroundColor(getResources().getColor(R.color.skyblue));
    }

    private void GetQuestion() {
        String SqlComm="Exec KeyPoint_FarbicPBGetQuestion @OPERTYPE='QUESTION',@UserNo='"+curLoginUserNo+"',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }

    //显示工序选择
    private void showSelPurchase(){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View findpurchase=inflater.inflate(R.layout.fragment_fabric_findpurchase, null);
        purchaseListGrid=findpurchase.findViewById(R.id.purchaseListGrid);
        final Button btn_proc_style_find=findpurchase.findViewById(R.id.btn_proc_style_find);
        edit_findOrderNo =findpurchase.findViewById(R.id.edit_findOrderNo);
        edit_findOrderNo.setText(txt_OrderNo.getText().toString());
        btn_proc_style_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideIM(v);
                //调用数据;
                refreshPurchaseList(curDepartNo, edit_findOrderNo.getText().toString());
            }
        });
        purchaseListGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    selOrderNo= PurchaseJSONArray.getJSONObject(position).getString("OrderNo");
                    selStyleNo = PurchaseJSONArray.getJSONObject(position).getString("StyleNo");
                    selVatNo = PurchaseJSONArray.getJSONObject(position).getString("VatNo");
                    selKeyFormNo= PurchaseJSONArray.getJSONObject(position).getString("KeyFormNo");
                    selBaleName = PurchaseJSONArray.getJSONObject(position).getString("BaleName");
                    selColor= PurchaseJSONArray.getJSONObject(position).getString("Color");
                    selFabricElement= PurchaseJSONArray.getJSONObject(position).getString("FabricElement");
                    selFabricWidth= PurchaseJSONArray.getJSONObject(position).getString("FabricWidth");
                    selGramWeight= PurchaseJSONArray.getJSONObject(position).getString("GramWeight");
                    selNeedWeight= PurchaseJSONArray.getJSONObject(position).getString("NeedWeight");
                    selReadyWeight= PurchaseJSONArray.getJSONObject(position).getString("ReadyWeight");
                    selOwenNum= PurchaseJSONArray.getJSONObject(position).getString("OwenNum");
                } catch (JSONException e) {
                    e.printStackTrace();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }

            }
        });
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(findpurchase).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selOrderNo.length()>0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            edt_VatNo.setEnabled(true);
                            edt_PieceNo.setEnabled(true);
                            edt_PieceNo.setText("");
                            edit_RealFabricWidth.setText("");
                            edt_PieceLength.setText("");
                            edt_PieceWeight.setText("");
                            edt_CurLenValue.setText("");
                            //选合同;
                            txt_OrderNo.setText(selOrderNo);
                            txt_BaleName.setText(selBaleName);
                            txt_Color.setText(selColor);
                            txt_StyleNo.setText(selStyleNo);
                            txt_FabricWidth.setText(selFabricWidth);
                            txt_GramWeight.setText(selGramWeight);
                            txt_NeedWeight.setText(selNeedWeight);
                            txt_ReadyWeight.setText(selReadyWeight);
                            edt_VatNo.setText(selVatNo);
                            edt_CurLenValue.setText(selOwenNum);
                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请通过点击选中需要查询的款式！");
                            curToast.show();
                        }
                    }
                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Field field = null;
                try {
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle("选择采购合同");
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 1200;
        params.height = 700 ;
        alterDialog.getWindow().setAttributes(params);
        System.out.println("PurchaseJSONArray"+PurchaseJSONArray);
        //显示数据
        if (PurchaseJSONArray!=null){
            Message message = new Message();
            message.what = MSG_Purchase;
            fragmentHandler.removeMessages(message.what);
            fragmentHandler.sendMessage(message);
        }

    }

    private void refreshPurchaseList(String curDepartNo, String paramOrderNo) {
        String SqlComm = "Exec KeyPoint_FabricPBGetPurchase @OperType='GetPurchase',@DepartNo='"+curDepartNo+"',@OrderNo='"+paramOrderNo+"'";
        ReadSQLData(SqlComm);
    }

    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //设置焦点
        System.out.println(getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    //初始化;
    public void InitView(View view){
        chk_isYT=view.findViewById(R.id.chk_isYT);
        chk_isCJ=view.findViewById(R.id.chk_isCJ);
        waitDialog= new ProgressDialog(getContext());
        waitDialog.setTitle(getString(R.string.SystemHint));
        txt_PackEmpName=view.findViewById(R.id.txt_PackEmpName);
        txt_PackEmpName.setOnClickListener(this);
        txt_CheckEmpName=view.findViewById(R.id.txt_CheckEmpName);
        txt_CheckEmpName.setOnClickListener(this);
        btn_ManuQuestion=view.findViewById(R.id.btn_ManuQuestion);
        btn_ManuQuestion.setOnClickListener(this);
        btn_find = (Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Query = (Button)view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        view.findViewById(R.id.btn_SelectPurchase).setOnClickListener(this);
        view.findViewById(R.id.btn_ResetWeight).setOnClickListener(this);
        view.findViewById(R.id.btn_CancelWeight).setOnClickListener(this);
        txt_HintInfo = (TextView)view.findViewById(R.id.txt_HintInfo);
        gv_Question = (GridView)view.findViewById(R.id.gv_Question);
        gv_Question.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> param1AdapterView, View view, int position, long param1Long) {
                try {
                    txt_Question.setText(questionJson.optJSONObject(position).getString("FabricQuestion"));
                    selFabricCode = questionJson.optJSONObject(position).getString("FabricCode");
                    selFabricQuestion = questionJson.optJSONObject(position).getString("FabricQuestion");
                    return;
                } catch (JSONException jSONException) {
                    jSONException.printStackTrace();
                    return;
                }
            }
        });
        lv_BadList = (ListView)view.findViewById(R.id.lv_BadList);
        lv_BadList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                final int postion=i;
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setTitle(getString(R.string.SystemHint)).setMessage("您确定要删除选中的疵点记录吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                System.out.println(postion+"badJSON:"+badJSON);
                                badJSON.remove(postion);
                                System.out.println("badJSON:"+badJSON);
                                lv_BadList.setAdapter((ListAdapter)badListAdapter);
                            }}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).create();
                alertDialog.show(); // 显示对话框
                return true;
            }
        });
        txt_OrderNo = (TextView)view.findViewById(R.id.txt_OrderNo);
        txt_BaleName = (TextView)view.findViewById(R.id.txt_BaleName);
        txt_Color = (TextView)view.findViewById(R.id.txt_Color);
        txt_StyleNo = (TextView)view.findViewById(R.id.txt_StyleNo);
        txt_FabricWidth = (TextView)view.findViewById(R.id.txt_FabricWidth);
        txt_GramWeight = (TextView)view.findViewById(R.id.txt_GramWeight);
        txt_NeedWeight= (TextView)view.findViewById(R.id.txt_NeedWeight);
        txt_ReadyWeight= (TextView)view.findViewById(R.id.txt_ReadyWeight);
        view_oneBtn = (Button)view.findViewById(R.id.view_oneBtn);
        view_oneBtn.setOnClickListener(this);
        view_twoBtn = (Button)view.findViewById(R.id.view_twoBtn);
        view_twoBtn.setOnClickListener(this);
        view_threeBtn = (Button)view.findViewById(R.id.view_threeBtn);
        view_threeBtn.setOnClickListener(this);
        view_fourBtn = (Button)view.findViewById(R.id.view_fourBtn);
        view_fourBtn.setOnClickListener(this);
        view_fiveBtn = (Button)view.findViewById(R.id.view_fiveBtn);
        view_fiveBtn.setOnClickListener(this);
        view_sixBtn = (Button)view.findViewById(R.id.view_sixBtn);
        view_sixBtn.setOnClickListener(this);
        view_sevenBtn = (Button)view.findViewById(R.id.view_sevenBtn);
        view_sevenBtn.setOnClickListener(this);
        view_eightBtn = (Button)view.findViewById(R.id.view_eightBtn);
        view_eightBtn.setOnClickListener(this);
        view_nineBtn = (Button)view.findViewById(R.id.view_nineBtn);
        view_nineBtn.setOnClickListener(this);
        view_zeroBtn = (Button)view.findViewById(R.id.view_zeroBtn);
        view_zeroBtn.setOnClickListener(this);
        view_delBtn = (Button)view.findViewById(R.id.view_delBtn);
        view_delBtn.setOnClickListener(this);
        view_pointBtn = (Button)view.findViewById(R.id.view_pointBtn);
        view_pointBtn.setOnClickListener(this);
        view_clearBtn = (Button)view.findViewById(R.id.view_clearBtn);
        view_clearBtn.setOnClickListener(this);
        view_affirmBtn = (Button)view.findViewById(R.id.view_affirmBtn);
        view_affirmBtn.setOnClickListener(this);
        view_nextBtn = (Button)view.findViewById(R.id.view_nextBtn);
        view_nextBtn.setOnClickListener(this);
        view_saveWeight= (Button)view.findViewById(R.id.view_saveWeight);
        view_saveWeight.setOnClickListener(this);
        System.out.println("initView:A");
        btn_UpdateQuestion = (Button)view.findViewById(R.id.btn_UpdateQuestion);
        btn_UpdateQuestion.setOnClickListener(this);
        System.out.println("initView:A1");
        btn_QuestionClear = (Button)view.findViewById(R.id.btn_QuestionClear);
        btn_QuestionClear.setOnClickListener(this);
        System.out.println("initView:A2");
        btn_QuestionAdd = (Button)view.findViewById(R.id.btn_QuestionAdd);
        btn_QuestionAdd.setOnClickListener(this);
        System.out.println("initView:B");
        btn_One = (Button)view.findViewById(R.id.btn_One);
        btn_One.setOnClickListener(this);
        btn_Two = (Button)view.findViewById(R.id.btn_Two);
        btn_Two.setOnClickListener(this);
        btn_Three = (Button)view.findViewById(R.id.btn_Three);
        btn_Three.setOnClickListener(this);
        btn_Four = (Button)view.findViewById(R.id.btn_Four);
        btn_Four.setOnClickListener(this);
        view.findViewById(R.id.btn_Four2).setOnClickListener(this);
        view.findViewById(R.id.btn_Four3).setOnClickListener(this);
        System.out.println("initView:C");
        txt_Question = (TextView)view.findViewById(R.id.txt_Question);
        edt_VatNo = (EditText)view.findViewById(R.id.edt_VatNo);
        edt_VatNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent != null) {
                    System.out.println(keyEvent);
                    if (keyEvent.getAction() == 0 && keyEvent.getKeyCode() == 66) {
                        playRingtone();
                        hideIM(view);
                        Message message = new Message();
                        message.what = MSG_FocusBarcode;
                        fragmentHandler.removeMessages(message.what);
                        fragmentHandler.sendMessage(message);
                    }
                }
                return false;
            }

        });
        //edt_VatNo.setOnClickListener(this);
        edt_CurLenValue = (EditText)view.findViewById(R.id.edt_CurLenValue);
        edt_CurLenValue.setOnClickListener(this);
        edt_PieceNo = (EditText)view.findViewById(R.id.edt_PieceNo);
        edt_PieceNo.setOnClickListener(this);
        edit_RealFabricWidth = (EditText)view.findViewById(R.id.edit_RealFabricWidth);
        edit_RealFabricWidth.setOnClickListener(this);
        edt_PieceLength = (EditText)view.findViewById(R.id.edt_PieceLength);
        edt_PieceLength.setOnClickListener(this);
        edt_PieceWeight = (EditText)view.findViewById(R.id.edt_PieceWeight);
        edt_PieceWeight.setOnClickListener(this);
        edt_PieceWeight.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b==false){
                    CalcLength(edt_PieceWeight.getText().toString());
                }
            }
        });
        edt_BadWeight= (EditText)view.findViewById(R.id.edt_BadWeight);
        edt_BadWeight.setOnClickListener(this);
        edt_RectNo= (EditText)view.findViewById(R.id.edt_RectNo);
        edt_RectNo.setOnClickListener(this);
        edt_RealWeight = (EditText)view.findViewById(R.id.edt_RealWeight);
        edt_RealWeight.setOnClickListener(this);
        System.out.println("initView:D");
        btn_editBarcode = (ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        System.out.println("initView:E");
        edt_barcode = (EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(0);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        playRingtone();
                        hideIM(v);
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        }
                        //edt_VatNo.setEnabled(false);
                        //edt_PieceNo.setEnabled(false);
                        //未有焦点
                        scanBarcodeData(edt_barcode.getText().toString());
                        //发消息置焦点
                        Message msg =new Message();
                        msg.what = MSG_FocusBarcode;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }

                }
                return false;
            }
        });
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    private void showEditBad(){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View pull_input=inflater.inflate(R.layout.input_question, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final EditText edt_Question=pull_input.findViewById(R.id.edt_Question);
        final EditText edt_Deduct=pull_input.findViewById(R.id.edt_Deduct);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(pull_input).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (edt_Question.getText().length()>0){
                            JSONObject jSONObject = new JSONObject();
                            try {
                                jSONObject.put("FabricDeID", FabricDeID);
                                jSONObject.put("Question",  edt_Question.getText().toString());
                                jSONObject.put("FabricCode", "Manu");
                                jSONObject.put("FabricQuestion",edt_Question.getText().toString());
                                jSONObject.put("Place", edt_PieceLength.getText().toString());
                                jSONObject.put("Deduct", edt_Deduct.getText().toString());
                            } catch (JSONException jSONException) {
                                jSONException.printStackTrace();
                            }
                            badJSON.put(jSONObject);
                            System.out.println("badJSON:"+badJSON);
                            txt_Question.setText("");
                            lv_BadList.setAdapter((ListAdapter)badListAdapter);
                            hideIM(pull_input);
                        }
                    }
                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                hideIM(pull_input);
                Log.v("tag","取消");
            }
        }).setTitle("博大EFS系统");
        builder.show();
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        hideBottomUIMenu();
        //任意消息来均置焦点
        if (edt_barcode.isFocused()==false) setEditBarcodeFocus();
        else edt_barcode.selectAll();
        Bundle paramBundle = new Bundle();
        switch (v.getId()) {
            case R.id.txt_CheckEmpName:
            case R.id.txt_PackEmpName:
                showSelectEmployee((TextView)v);
                break;
            case R.id.btn_ManuQuestion:
                showEditBad();
                break;
            case R.id.btn_SelectPurchase:
                //showSelPurchase();
                //重新查一遍
                scanBarcodeData(PrBarcode);
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_ResetWeight:
                fragmentParams.clear();
                fragmentParams.put("ParamComm","WeightReset");//命令;
                fragmentParams.put("Text","T");//命令;
                mFragmentFabricCallBack.FragmentFabricWorkAndTransParams(fragmentParams);
                break;
            case R.id.btn_CancelWeight:
                fragmentParams.clear();
                fragmentParams.put("ParamComm","WeightReset");//命令;
                fragmentParams.put("Text","C");//命令;
                mFragmentFabricCallBack.FragmentFabricWorkAndTransParams(fragmentParams);
                break;
            case R.id.view_pointBtn:
                String fh=((Button)v).getText().toString();
                if (fh.equals(".")) {
                    System.out.println("AindexOf:" + edt_CurSelect.getText().toString().indexOf("."));
                    if (edt_CurSelect.getText().toString().indexOf(".") == -1 && edt_CurSelect.getText().toString().indexOf("/") == -1) {
                        edt_CurSelect.getText().append(".");
                        return;
                    }
                } else{
                    edt_CurSelect.getText().append(fh);
                }
                break;
            case R.id.view_nextBtn:
                if (edt_CurSelect != null && edt_CurSelect.getId() != R.id.edt_PieceWeight) {
                    nextEdit();
                    return;
                }
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                if (edt_CurSelect != null) {
                    edt_CurSelect.getText().append(((Button) v).getText());
                    CalcLength(edt_PieceWeight.getText().toString());
                    return;
                }
                break;
            case R.id.view_delBtn:
                if (edt_CurSelect.getText().length() > 0) {
                    edt_CurSelect.setSelection(edt_CurSelect.getText().length());
                    int start = edt_CurSelect.getSelectionStart();
                    edt_CurSelect.getText().delete(start - 1, start);
                    CalcLength(edt_PieceWeight.getText().toString());
                }
                break;
            case R.id.view_clearBtn:
                edt_CurSelect.setText("");
                return;
            case R.id.view_saveWeight:
                if (PrFabricMaID.length()>0){
                    String SqlComm = "Exec KeyPoint_PBFabricSaveWeight @OperType='SaveWeight',@PrFabricMaID='" + PrFabricMaID + "',@Weight='"+edt_PieceWeight.getText().toString()+ "',@PrBarcode='"+PrBarcode+"',@CPUID='"+CPUID+"'";
                    ReadSQLData(SqlComm);
                } else{
                    curToast.setText("请先点击确定保存数据!");
                    curToast.show();
                }
                break;
            case R.id.view_affirmBtn:
                selRectNo=edt_RectNo.getText().toString();
                selBadWeight=edt_BadWeight.getText().toString();
                System.out.println("edt_BadWeight1:"+edt_BadWeight.getText().toString());
                if (edt_CurSelect != null && edt_CurSelect.getId() != R.id.edt_PieceWeight) {
                    if (edit_RealFabricWidth.getText().length() == 0) {
                        setActiveEdt(edit_RealFabricWidth);
                        return;
                    }
                    if (edit_RealFabricWidth.getText().length() == 0) {
                        setActiveEdt(edit_RealFabricWidth);
                        return;
                    }
                    if (edt_PieceLength.getText().length() == 0) {
                        setActiveEdt(edt_PieceLength);
                        return;
                    }
                    if (edt_RealWeight.getText().length() == 0) {
                        setActiveEdt(edt_RealWeight);
                        return;
                    }
                    if (edt_PieceWeight.getText().length() == 0) {
                        setActiveEdt(edt_PieceWeight);
                        return;
                    }
                }
                if (txt_OrderNo.getText().length() == 0) {
                    curToast.setText("请先扫描条码获取订单信息!");
                    curToast.show();
                    return;
                }
                if (selPackEmpName.length()==0){
                    curToast.setText("请选择包装员工!!");
                    curToast.show();
                    return;
                }
                if (edt_PieceWeight.getText().length()>0){
                    if (Float.parseFloat(edt_PieceWeight.getText().toString())<0){
                        curToast.setText("重量数量为0，请检查!");
                        curToast.show();
                        return;
                    }
                }
                if (txt_PackEmpName.getText().length()==0||txt_CheckEmpName.getText().length()==0){
                    curToast.setText("请选择包装工、检查工!");
                    curToast.show();
                    return;
                }
                if (edt_VatNo.getText().length() > 0 && edit_RealFabricWidth.getText().length() > 0  && edt_PieceLength.getText().length() > 0 && edt_PieceWeight.getText().length() > 0) {
                    if ((badJSON==null||badJSON.length() == 0)&&chk_isCJ.isChecked()) {
                        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                .setTitle(getString(R.string.SystemHint)).setMessage("疵点未输入,确定本匹没有疵点吗?")
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        hideBottomUIMenu();
                                        checkSaveFabric(txt_OrderNo.getText().toString(),selBaleCode,selBaleName,txt_Color.getText().toString(),edt_VatNo.getText().toString(),edt_PieceNo.getText().toString(),edt_CurLenValue.getText().toString());
                                    }
                                }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        return;
                    }
                    checkSaveFabric(txt_OrderNo.getText().toString(),selBaleCode,selBaleName,txt_Color.getText().toString(),edt_VatNo.getText().toString(),edt_PieceNo.getText().toString(),edt_CurLenValue.getText().toString());
                    return;
                }
                curToast.setText("请将数据输入完整!");
                curToast.show();
                break;
            case R.id.edt_VatNo:
            case R.id.edt_PieceNo:
            case R.id.edit_RealFabricWidth:
            case R.id.edt_RealWeight:
            case R.id.edt_PieceLength:
            case R.id.edt_PieceWeight:
            case R.id.edt_CurLenValue:
            case R.id.edt_BadWeight:
            case R.id.edt_RectNo:
                if (edt_CurSelect != null) edt_CurSelect.setBackground(null);
                edt_CurSelect = (EditText)v;
                edt_CurSelect.setBackgroundColor(getResources().getColor(R.color.skyblue));
                break;
            case R.id.btn_find:
                if (edt_barcode.getText().length() > 0) {
                    scanBarcodeData(edt_barcode.getText().toString());
                    break;
                }
                curToast.setText("请先输入条码！");
                curToast.show();
                return;
            case R.id.edt_barcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                InputMethodManager imm2 = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm2.showSoftInput(edt_barcode, InputMethodManager.SHOW_FORCED);
                return;
            case R.id.btn_QuestionClear:
                ClearBadData();
                return;
            case R.id.btn_UpdateQuestion:
                GetQuestion();
                break;

            case R.id.btn_Query:
                Intent intent = new Intent(getContext(), QueryActivity.class);
                Bundle bundle = new Bundle();
                bundle.clear();
                bundle.putString("LoginUserNo", curLoginUserNo);
                bundle.putString("LoginUser", curLoginUser);
                bundle.putString("CurDepartNo", curDepartNo);
                bundle.putString("CurDepart", curDepart);
                bundle.putString("ServiceUrl", curServiceUrl);
                bundle.putString("ServiceDir", curServiceDir);
                bundle.putString("CPUID", CPUID);
                bundle.putString("QueryTitle", "坯布检查查询");
                bundle.putString("OrderNo", txt_OrderNo.getText().toString());
                bundle.putString("NeedOrder", "NO");
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.btn_One:
            case R.id.btn_Two:
            case R.id.btn_Three:
            case R.id.btn_Four:
            case R.id.btn_Four2:
            case R.id.btn_Four3:
                if (txt_Question.getText().toString().length() > 0) {
                    String deduct = ((Button)v).getTag().toString();
                    JSONObject jSONObject = new JSONObject();
                    try {
                        jSONObject.put("FabricDeID", FabricDeID);
                        jSONObject.put("Question", txt_Question.getText().toString());
                        jSONObject.put("FabricCode", selFabricCode);
                        jSONObject.put("FabricQuestion", selFabricQuestion);
                        jSONObject.put("Place", edt_PieceLength.getText().toString());
                        jSONObject.put("Deduct", deduct);
                    } catch (JSONException jSONException) {
                        jSONException.printStackTrace();
                    }
                    badJSON.put(jSONObject);
                    System.out.println("badJSON:"+badJSON);
                    txt_Question.setText("");
                    lv_BadList.setAdapter((ListAdapter)badListAdapter);
                    break;
                }
                curToast.setText("请选择面料疵点!");
                curToast.show();
                break;
            default:
                break;
        }
    }



    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType = "";
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        System.out.println(jsonArray);
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true)
                            OperType = jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType") == true)
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                        if (OperType.toUpperCase().equals("SCANBARCODE") || (OperType.equals("SaveWeight"))) {
                            resultJSON = jsonArray;
                            Message message = new Message();
                            message.what = MSG_SCANBARCODE;
                            fragmentHandler.removeMessages(message.what);
                            fragmentHandler.sendMessage(message);
                        }
                        if (OperType.toUpperCase().equals("QUESTION")) {
                            System.out.println("获取到面料疵点");
                            questionJson = jsonArray;
                            if (tmpdb == null) OpenCreateDB();
                            try {
                                tmpdb.execSQL("Delete from FabricCode");
                                for (int i = 0; i < questionJson.length(); i++) {
                                    tmpdb.execSQL("Insert into FabricCode(FabricCode,FabricQuestion) values(?,?)",
                                            new Object[]{questionJson.optJSONObject(i).getString("FabricCode"),
                                                    questionJson.optJSONObject(i).getString("FabricQuestion")});
                                }
                                Message message = new Message();
                                message.what = MSG_QuestionOver;
                                fragmentHandler.removeMessages(message.what);
                                fragmentHandler.sendMessage(message);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Message message = new Message();
                                message.what = MSG_ERRMSG;
                                Bundle bundle = new Bundle();
                                bundle.putString("Hint", "QC代码暂存出错:" + e.getMessage());
                                fragmentHandler.removeMessages(message.what);
                                fragmentHandler.sendMessage(message);
                            }
                        }
                        if (OperType.toUpperCase().equals("SaveTrans".toUpperCase())) {
                            System.out.println("提交处理完成");
                            resultJSON = jsonArray;
                            Message message = new Message();
                            message.what = MSG_SUBMIT;
                            Bundle bundle = new Bundle();
                            bundle.putString("Hint", "提交处理完成");
                            fragmentHandler.removeMessages(message.what);
                            fragmentHandler.sendMessage(message);
                            return;
                        }
                        if (OperType.toUpperCase().equals("GetPurchase".toUpperCase())) {
                            System.out.println("提交处理完成");
                            PurchaseJSONArray = jsonArray;
                            Message message = new Message();
                            message.what = MSG_Purchase;
                            fragmentHandler.removeMessages(message.what);
                            fragmentHandler.sendMessage(message);
                            return;
                        }

                        if (OperType.toUpperCase().equals("ShowPurchase".toUpperCase())) {
                            System.out.println("提交处理完成");
                            PurchaseJSONArray = jsonArray;
                            Message message = new Message();
                            message.what = MSG_ShowPurchase;
                            fragmentHandler.removeMessages(message.what);
                            fragmentHandler.sendMessage(message);
                            return;
                        }
                        if (OperType.toUpperCase().equals("GetEmployee".toUpperCase())) {
                            System.out.println("员工获取成功");
                            employeeJson = jsonArray;

                            return;
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            Message message = new Message();
                            message.what = MSG_ERRMSG;
                            Bundle bundle = new Bundle();
                            bundle.putString("Hint", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            message.setData(bundle);
                            fragmentHandler.sendMessage(message);
                        }

                    } else {
                        Message message = new Message();
                        message.what = MSG_ERRMSG;
                        Bundle bundle = new Bundle();
                        bundle.putString("Hint", "未返回任何数据!");
                        fragmentHandler.removeMessages(message.what);
                        fragmentHandler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = MSG_ERRMSG;
                    Bundle bundle = new Bundle();
                    bundle.putString("Hint", e.getMessage().toString());
                    message.setData(bundle);
                    fragmentHandler.sendMessage(message);
                }

            }
        };
        new Thread(run).start();

    }

    //确认面料
    private void affirmFabric() {
        JSONObject jSONObject = new JSONObject();
        try {
            fabricJSON = new JSONArray("[]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        FabricDeID = UUID.randomUUID().toString();
        try {
            jSONObject.put("FabricDeID", FabricDeID);
            jSONObject.put("KeyID", selKeyID);
            jSONObject.put("VatNo", edt_VatNo.getText().toString());
            jSONObject.put("PieceNo", edt_PieceNo.getText().toString());
            jSONObject.put("PieceStart", "0");
            jSONObject.put("PieceMiddle", "0");
            jSONObject.put("PieceEnd","0");
            jSONObject.put("PieceLength", edt_PieceLength.getText().toString());
            jSONObject.put("PieceWeight", edt_PieceWeight.getText().toString());
            jSONObject.put("RealWeight", edt_RealWeight.getText().toString());
            jSONObject.put("RealFabricWidth", edit_RealFabricWidth.getText().toString());
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        fabricJSON.put(jSONObject);
        if (tmpdb == null) OpenCreateDB();
        tmpdb.execSQL("Delete from FabricBad", new Object[0]);
        if (badJSON != null)
            for (int i = 0; i < badJSON.length(); i++) {
                try {
                    tmpdb.execSQL("Insert into FabricBad(FabricDeID,FabricCode,FabricQuestion,Place,Deduct) values(?,?,?,?,?)",
                            new Object[] { FabricDeID, badJSON.optJSONObject(i).getString("FabricCode"), badJSON.optJSONObject(i).getString("FabricQuestion"),
                                    badJSON.optJSONObject(i).getString("Place"), badJSON.optJSONObject(i).getString("Deduct") });
                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("Hint","QC代码暂存完成："+e.getMessage());
                    fragmentHandler.removeMessages(message.what);
                    fragmentHandler.sendMessage(message);
                }
            }
        if (PrBarcode.length()>0) ClearScreen();
        putFabricList(selOrderNo, selBaleCode, selBaleName, selColor,selFabricElement,selFabricWidth,selGramWeight,selNeedWeight,selRectNo,selBadWeight);
        ClearScreen();
        System.out.println(fabricJSON);
    }


    private void fillScreen() {
        if (resultJSON.length() > 0)
            try {

                if (resultJSON.getJSONObject(0).has("ClearData") == true) {
                    if (resultJSON.getJSONObject(0).getString("ClearData").equals("Y")
                            ||resultJSON.getJSONObject(0).getString("ClearData").equals("YES"))
                        ClearScreen();
                }
                if (resultJSON.getJSONObject(0).has("OrderNo") == true) {
                    selOrderNo = resultJSON.getJSONObject(0).getString("OrderNo");
                    txt_OrderNo.setText(selOrderNo);
                }
                if (resultJSON.getJSONObject(0).has("KeyID") == true)
                    selKeyID = resultJSON.getJSONObject(0).getString("KeyID");
                if (resultJSON.getJSONObject(0).has("BaleCode") == true)
                    selBaleCode = resultJSON.getJSONObject(0).getString("BaleCode");
                if (resultJSON.getJSONObject(0).has("BaleName") == true) {
                    selBaleName = resultJSON.getJSONObject(0).getString("BaleName");
                    txt_BaleName.setText(selBaleName);
                }
                if (resultJSON.getJSONObject(0).has("OwenNum") == true) {
                    edt_CurLenValue.setText(resultJSON.getJSONObject(0).getString("OwenNum"));
                }
                if (resultJSON.getJSONObject(0).has("Color") == true) {
                    selColor = resultJSON.getJSONObject(0).getString("Color");
                    txt_Color.setText(selColor);
                }
                if (resultJSON.getJSONObject(0).has("StyleNo") == true) {
                    selStyleNo = resultJSON.getJSONObject(0).getString("StyleNo");
                    txt_StyleNo.setText(selStyleNo);
                }
                if (resultJSON.getJSONObject(0).has("FabricWidth") == true) {
                    selFabricWidth = resultJSON.getJSONObject(0).getString("FabricWidth");
                    txt_FabricWidth.setText(selFabricWidth);
                }
                if (resultJSON.getJSONObject(0).has("GramWeight") == true) {
                    selGramWeight = resultJSON.getJSONObject(0).getString("GramWeight");
                    txt_GramWeight.setText(selGramWeight);
                }
                if (resultJSON.getJSONObject(0).has("NeedWeight") == true) {
                    selNeedWeight = resultJSON.getJSONObject(0).getString("NeedWeight");
                    txt_NeedWeight.setText(selNeedWeight);
                }
                if (resultJSON.getJSONObject(0).has("ReadyWeight") == true) {
                    selReadyWeight = resultJSON.getJSONObject(0).getString("ReadyWeight");
                    txt_ReadyWeight.setText(selReadyWeight);
                }
                if (resultJSON.getJSONObject(0).has("VatNo") == true) {
                    edt_VatNo.setText(resultJSON.getJSONObject(0).getString("VatNo"));
                    //setActiveEdt(edt_PieceNo);
                }
                if (resultJSON.getJSONObject(0).has("PieceNo") == true) {
                    edt_PieceNo.setText(resultJSON.getJSONObject(0).getString("PieceNo"));
                    setActiveEdt(edit_RealFabricWidth);
                }
                if (resultJSON.getJSONObject(0).has("NeedWeight") == true) {
                    txt_NeedWeight.setText(resultJSON.getJSONObject(0).getString("NeedWeight"));
                }
                if (resultJSON.getJSONObject(0).has("KeyFormNo") == true) {
                    selKeyFormNo=resultJSON.getJSONObject(0).getString("KeyFormNo");
                }
                if (resultJSON.getJSONObject(0).has("RealFabricWidth") == true)
                    edit_RealFabricWidth.setText(resultJSON.getJSONObject(0).getString("RealFabricWidth"));
                if (resultJSON.getJSONObject(0).has("PieceLength") == true)
                    edt_PieceLength.setText(resultJSON.getJSONObject(0).getString("PieceLength"));
                if (resultJSON.getJSONObject(0).has("PieceWeight") == true)
                    edt_PieceWeight.setText(resultJSON.getJSONObject(0).getString("PieceWeight"));
                if (resultJSON.getJSONObject(0).has("HintInfo") == true)
                    txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("HintInfo"));
                if (resultJSON.getJSONObject(0).has("ResultInfo") == true) {
                    txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("ResultInfo"));
                    curToast.setText(txt_HintInfo.getText().toString());
                    curToast.show();
                }
                if (resultJSON.getJSONObject(0).has("ErrInfo") == true) {
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle("系统提示").setMessage(resultJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                    return;
                }
                Message message = new Message();
                message.what = MSG_FocusBarcode;
                fragmentHandler.removeMessages(message.what);
                fragmentHandler.sendMessage(message);
            } catch (JSONException jSONException) {
                jSONException.printStackTrace();
            }
    }

    public final class BadListAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public BadListAdapter(Context context) {
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return badJSON.length();
        }

        public Object getItem(int position) {
            try {
                return badJSON.get(position);
            } catch (JSONException jSONException) {
                jSONException.printStackTrace();
                return null;
            }
        }

        public long getItemId(int position) {
            return position;
        }
        public View getView(int position, View convertView, ViewGroup parent) {
            View view =  inflater.inflate(R.layout.fragment_fabric_baditem, null, false);
            try {
                Integer textColor = Integer.valueOf(getResources().getColor(R.color.text_black));
                if (badJSON.optJSONObject(position).has("ConColor")) {
                    if (badJSON.optJSONObject(position).getString("ConColor").equals("1"))
                        textColor = Integer.valueOf(getResources().getColor(R.color.green));
                    if (badJSON.optJSONObject(position).getString("ConColor").equals("2"))
                        textColor = Integer.valueOf(getResources().getColor(R.color.red));
                }
                TextView textView = (TextView)view.findViewById(R.id.item_Question);
                if (badJSON.optJSONObject(position).has("Question") == true)
                    textView.setText(badJSON.optJSONObject(position).getString("Question"));
                textView.setTextColor(textColor);
                textView = (TextView)view.findViewById(R.id.item_Place);
                if (badJSON.optJSONObject(position).has("Place") == true)
                    textView.setText(badJSON.optJSONObject(position).getString("Place"));
                textView.setTextColor(textColor);
                textView = (TextView)view.findViewById(R.id.item_Deduct);
                if (badJSON.optJSONObject(position).has("Deduct") == true)
                    textView.setText(badJSON.optJSONObject(position).getString("Deduct"));
                textView.setTextColor(textColor);
            } catch (JSONException jSONException) {
                jSONException.printStackTrace();
                System.out.println(jSONException.getMessage());
            }
            Log.d("msg", "BadListAdapter_position"+position);
            return view;
        }
    }


    public final class QuestionGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public QuestionGridAdapter(Context context) {
            inflater =  (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return questionJson.length();
        }

        public Object getItem(int position) {
            try {
                return questionJson.get(position);
            } catch (JSONException jSONException) {
                jSONException.printStackTrace();
                return null;
            }
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View contentView, ViewGroup viewGroup) {
            contentView = inflater.inflate(R.layout.fragment_fabric_questionitem, null, false);
            try {
                Log.d(TAG, "getView()----------------------------------------------------->"+position);
                if (questionJson.optJSONObject(position).has("FabricCode") == true && questionJson.optJSONObject(position).has("FabricQuestion") == true) {
                    TextView textView = (TextView)contentView.findViewById(R.id.item_QuestionName);
                    textView.setText(questionJson.optJSONObject(position).getString("FabricCode")+"."+questionJson.optJSONObject(position).getString("FabricQuestion"));
                }
            } catch (JSONException jSONException) {
                jSONException.printStackTrace();
                System.out.println(jSONException.getMessage());
            }
            Log.d("msg", "QuestionGridAdapter_position:"+position);
            return contentView;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println(getClass().getName()+" 设置焦点-------------------------------1.Start");
        setEditBarcodeFocus();
        System.out.println(getClass().getName()+" 设置焦点-------------------------------1.End");

    }

    @Override
    public void onResume() {

        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {

        super.onHiddenChanged(hidden);
    }
}

